<?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\View\View;

class CategoryController extends Controller
{
    /**
     * 显示分类下的文章列表
     *
     * @param string $slug
     * @param Request $request
     * @return View
     */
    public function show(string $slug, Request $request): View
    {
        $category = Category::where('slug', $slug)->firstOrFail();

        $query = Post::with(['category', 'tags', 'user'])
            ->where('category_id', $category->id)
            ->where('status', 'published')
            ->whereNotNull('published_at')
            ->where('published_at', '<=', now())
            ->orderBy('published_at', 'desc');

        // 搜索
        if ($request->has('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                  ->orWhere('excerpt', 'like', "%{$search}%")
                  ->orWhere('content', 'like', "%{$search}%");
            });
        }

        $posts = $query->paginate(12);

        // 获取子分类
        $childCategories = Category::where('parent_id', $category->id)
            ->orderBy('name')
            ->get();

        return view('categories.show', compact('category', 'posts', 'childCategories'));
    }

    /**
     * 显示所有分类列表
     *
     * @return View
     */
    public function index(): View
    {
        $categories = Category::with(['posts' => function ($query) {
                $query->where('status', 'published')
                      ->whereNotNull('published_at')
                      ->where('published_at', '<=', now());
            }])
            ->whereNull('parent_id')
            ->orderBy('name')
            ->get();

        return view('categories.index', compact('categories'));
    }
}